/**
 * 文件全局变量获取接口测试用例
 *
 * Created by snowingsea on 2020/03/06.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmark = require('./../../../benchmark/analyse-files/logic_bombs');

const files = require('./../../../../phoenix/models/files');

module.exports = describe('/GET files/:id/globals.json', function () {
  const administrator = new Administrator();
  const extensions = benchmark.config.languages.c.suffixes
    .concat(benchmark.config.headers.suffixes);
  let rootDirectory;
  const newUserIds = [];
  function url(fileId) {
    return `/files/${fileId}/globals.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((projectVersion) => {
        rootDirectory = projectVersion.rootDirectory;
        return projectVersion.updateVersionFiles(benchmark.files, benchmark.config);
      })
      .then(() => rootDirectory.analyse())
      .then(() => rootDirectory.getTree(extensions))
      .then((tree) => {
        common.should.be.fileTreeMessage(tree);
        common.should.be.equal.tree(tree.tree, benchmark.result.tree);
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  // 正常请求
  it('it should GET globals', function (done) {
    rootDirectory.getTree(extensions)
      .then((tree) => {
        const allFiles = [];
        const rootArray = [tree.tree];
        while (rootArray.length > 0) {
          const root = rootArray.pop();
          if (root.children) {
            root.children.forEach((child) => {
              rootArray.push(child);
            });
          }
          allFiles.push(root);
        }
        const promises = allFiles.map((file) => {
          const { accessToken } = rootDirectory.projectVersion.project.creator.token;
          return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
            chai.request(uri)
              .get(url(file.fileId))
              .set('Authorization', `Bearer ${accessToken}`)
              .end((err, res) => {
                res.should.have.status(200);
                common.should.be.fileGlobalsMessage(res.body);
                if (file.kind === files.kind.directory
                  || file.status !== files.statusKind.compiled) {
                  Object.keys(res.body.globals).length.should.be.eql(0);
                }
                resolve();
              });
          });
        });
        return Promise.all(promises);
      })
      .then(() => {
        done();
      })
      .catch(done);
  });

  // 不可获取不存在文件的全局变量
  it('it should fail to get globals when the file is not exists', function (done) {
    let newFileId;
    rootDirectory.createEmptyFile()
      .then(({ fileId }) => {
        newFileId = fileId;
        return rootDirectory.removeFile(fileId);
      })
      .then(() => rootDirectory.projectVersion.project.creator.login())
      .then(() => {
        chai.request(uri)
          .get(url(newFileId))
          .set('Authorization', `Bearer ${rootDirectory.projectVersion.project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可获取他人项目文件的全局变量
  it('it should fail to get globals when the project is not yours', function (done) {
    let otherDirectoryId;
    administrator.createRandomTester()
      .then((newTester) => {
        newUserIds.push(newTester.userId);
        return newTester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then(({ rootDirectory }) => {
        otherDirectoryId = rootDirectory.fileId;
        return rootDirectory.projectVersion.project.creator.login();
      })
      .then(() => {
        chai.request(uri)
          .get(url(otherDirectoryId))
          .set('Authorization', `Bearer ${rootDirectory.projectVersion.project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
